local desc_hx__simulator = [[
  # 忆者简介
  ______________________

  回想当年种种，这次，你决定重入忆境。（测试阶段，目前仅支持1人游玩）

  <br/>是祸是福，一试便知。
]]


local HX = require "packages/huixiangkill/hxfs"

local hx__simulator_getLogic = function()
  local hx__simulator_logic = GameLogic:subclass("hx__simulator_logic")
   --关闭手杀特效
   function hx__simulator_logic:prepareForStart()
    local room = self.room
    self:addTriggerSkill(Fk.skills["game_rule"] --[[@as TriggerSkill]])
    for _, trig in ipairs(Fk.global_trigger) do
      if trig:getSkeleton().name ~= "mobile_effect" then
        self:addTriggerSkill(trig)
      end
    end
    for _, trig in ipairs(Fk.legacy_global_trigger) do
      self:addTriggerSkill(trig)
    end
    self.room:sendLog{ type = "$GameStart" }
  end

  function hx__simulator_logic:initialize(room)
    GameLogic.initialize(self, room)
    self.role_table = {
      nil,nil,nil,
      { "rebel", "rebel", "rebel", "rebel" },
    }
  end

  function hx__simulator_logic:assignRoles()
    local room = self.room
    local n = #room.players
    local roles = self.role_table[n]
    table.shuffle(roles)

    local players = room.players
    local targets = table.filter(room.players, function(p) return p.id > 0 end)
    local choices = {"#hx__simulator_choose1-1","#hx__simulator_choose1-2"}
    local result = room:askToJointChoice(room.players[1], {
      choices = choices,
      players = targets,
      prompt = "#hx__simulator_choose1",
    })
    local yizhes = {}
    for _, p in ipairs(targets) do
      if result[p] == "#hx__simulator_choose1-2" then
        table.insert(yizhes, p)
      end
    end
    if #yizhes > 0 then
      local chosen_lord = yizhes[math.random(#yizhes)]
      for _, p in ipairs(players) do
        if p == chosen_lord then
          room:setPlayerProperty(p, "role", "renegade")
          room:broadcastProperty(p, "role")
          room:setPlayerProperty(p, "role_shown", true)
        else
          room:setPlayerProperty(p, "role", "rebel")
          room:broadcastProperty(p, "role")
          room:setPlayerProperty(p, "role_shown", true)
        end
      end
    else
      for _, p in ipairs(players) do
        room:setPlayerProperty(p, "role", "rebel")
        room:broadcastProperty(p, "role")
        room:setPlayerProperty(p, "role_shown", true)
      end
    end
    local allyizhe = {}
    for _, p in ipairs(players) do
      if p.role == "renegade" then
        table.insert(allyizhe, p)
      end
    end
    room:setTag("hx__simulator_allyizhe", allyizhe)
  end

  --- 分配座位
  function hx__simulator_logic:adjustSeats()
    local player_circle = {}
    local room = self.room
    room:setBanner("@[:]huixiangmode_rule","hx__simulator-intro") --模式简介
    local players = self.room.players
    local p = 1
    for i = 1, #players do
      if HX.Isyizhe(room, players[i]) then
        p = i
        break
      end
    end
    for j = p, #players do
      table.insert(player_circle, players[j])
    end
    for j = 1, p - 1 do
      table.insert(player_circle, players[j])
    end

    self.room:arrangeSeats(player_circle)
  end


  -- function hx__simulator_logic:prepareDrawPile()
  --   local room = self.room
  --   local allCardIds = Fk:getAllCardIds()
  --   local filterCardIds = {}
  --   --卡牌白名单
  --   local white_cards = {"standard","standard_cards","maneuvering","tenyear_token","mobile_derived","ol_token","overseas_token"}
  --   for i = #allCardIds, 1, -1 do
  --     local id = allCardIds[i]
  --     local card = Fk:getCardById(id)
  --     if card then
  --       if card.is_derived or not table.contains(white_cards, card.package.name) then
  --         table.removeOne(allCardIds, id)
  --         table.insert(room.void, id)
  --         room:setCardArea(id, Card.Void, nil)
  --       end
  --       if table.contains(white_cards, card.package.name) then
  --         if not card.is_derived then
  --           table.insert(filterCardIds, id)
  --         end
  --       end
  --     end
  --   end
  --   local seed = math.random(2 << 32 - 1)
  --   table.shuffle(filterCardIds, seed)
  --   room.draw_pile = filterCardIds
  --   for _, id in ipairs(room.draw_pile) do
  --     room:setCardArea(id, Card.DrawPile, nil)
  --   end
  --   room:doBroadcastNotify("PrepareDrawPile", seed)
  -- end

  function hx__simulator_logic:chooseGenerals()
    local room = self.room ---@type Room
    local generalNum = room.settings.generalNum
    local n = room.settings.enableDeputy and 2 or 1
    for _, p in ipairs(room.players) do
      room:setPlayerProperty(p, "role_shown", true)
      room:broadcastProperty(p, "role")
    end

    
    local lord = HX.getyizhe(room)[1]
    if lord ~= nil then
      room:setCurrent(lord)
      local players = room.players
      local nonlord = room:getOtherPlayers(lord)
      local generals = table.random(room.general_pile, #room.players * generalNum)
      local lordgenerals = room:getNGenerals(#players * generalNum + 2)

      local req = Request:new(players, "AskForGeneral")
      for i, p in ipairs(players) do
        local arg = table.slice(generals, (i - 1) * generalNum + 1, i * generalNum + 1)
        if HX.Isyizhe(room, p) then
          local count = #lordgenerals -- 忆者福利：多发两个武将
          table.insert(arg, lordgenerals[count])
          table.insert(arg, lordgenerals[count - 1])
          req:setData(p, { arg, 1 })
          req:setDefaultReply(p, table.random(arg, 1))
        else
          req:setData(p, { arg, n })
          req:setDefaultReply(p, table.random(arg, n))
        end
      end

      local lord_result = req:getResult(lord)[1]
      room:setTag("hx__simulator_mode_lordgeneral", {lord_result})  --用于为忆者添加技能
      room:prepareGeneral(lord, "hxyiwu__yanjun")  --随机身份 FIXME:还没随机
      room:setPlayerMark(lord, "@&hx__simulator_mode_lordgeneral", {lord_result})  --真实身份

      for _, p in ipairs(nonlord) do
        local result = req:getResult(p)
        local general, deputy = result[1], result[2]
        room:prepareGeneral(p, general, deputy)
      end

      room:askToChooseKingdom(players)
      room:returnToGeneralPile(lordgenerals)
      room:setTag("SkipNormalDeathProcess", true)
    else
      local players = room.players
      lord = players[1]
      room:setCurrent(lord)
      local generals = table.random(room.general_pile, #room.players * generalNum)

      local req = Request:new(players, "AskForGeneral")
      for i, p in ipairs(players) do
        local arg = table.slice(generals, (i - 1) * generalNum + 1, i * generalNum + 1)
        req:setData(p, { arg, n })
        req:setDefaultReply(p, table.random(arg, n))
      end
      for _, p in ipairs(players) do
        local result = req:getResult(p)
        local general, deputy = result[1], result[2]
        room:prepareGeneral(p, general, deputy)
      end

      room:askToChooseKingdom(players)
      room:setTag("SkipNormalDeathProcess", true)
    end
  end

  function hx__simulator_logic:attachSkillToPlayers()
    local room = self.room
    local players = room.players
    local n = room.settings.enableDeputy and 2 or 1
    local addRoleModSkills = function(player, skillName)
      local skill = Fk.skills[skillName]
      if not skill then
        fk.qCritical("Skill: "..skillName.." doesn't exist!")
        return
      end
      if skill:hasTag(Skill.Lord) then return end

      -- if skill:hasTag(Skill.AttachedKingdom) and not
      -- table.contains(skill:getSkeleton().attached_kingdom, player.kingdom) then return end

      room:handleAddLoseSkills(player, skillName, nil, false,true)
      self:trigger(fk.EventAcquireSkill, player, {skill = skill, who = player})
    end
    for _, p in ipairs(room.alive_players) do
      for _, s in ipairs(Fk.generals[p.general]:getSkillNameList(false)) do
        addRoleModSkills(p, s)
      end
      if HX.Isyizhe(room, p) then  --不添加技能会怎么样
        local lord_result = room:getTag("hx__simulator_mode_lordgeneral")[1]
        for _, s in ipairs(Fk.generals[lord_result]:getSkillNameList(false)) do
          addRoleModSkills(p, s)
        end
      end
      local deputy = Fk.generals[p.deputyGeneral]
      if deputy then
        if HX.Isyizhe(room, p) then  --移除副将
          p.deputyGeneral = ""
          room:broadcastProperty(p, "deputyGeneral")
          --room:handleAddLoseSkills(p, "huixiang__fenghuo", nil, false)
        else
          for _, s in ipairs(deputy:getSkillNameList(true)) do
            addRoleModSkills(p, s)
          end
        end
      end
    end
  end
  return hx__simulator_logic
end

local hx__simulator_mode = fk.CreateGameMode{
  name = "hx__simulator_mode",
  minPlayer = 4,
  maxPlayer = 4,
  rule = "#hx__simulator_rule&",
  logic = hx__simulator_getLogic,
  is_counted = function(self, room)
    return #room.players >= 1
  end,
  build_draw_pile = function(self)
    local allCardIds = Fk:getAllCardIds()
    local filterCardIds = {}
    local void = {}
    --卡牌白名单
    local white_cards = {"standard","standard_cards","maneuvering","tenyear_token","mobile_derived","ol_token","overseas_token"}
    for i = #allCardIds, 1, -1 do
      local id = allCardIds[i]
      local card = Fk:getCardById(id)
      if card then
        if card.is_derived or not table.contains(white_cards, card.package.name) then
          table.removeOne(allCardIds, id)
          table.insert(void, id)
        end
        if table.contains(white_cards, card.package.name) then
          if not card.is_derived then
            table.insert(filterCardIds, id)
          end
        end
      end
    end
    return filterCardIds, void
  end,
  surrender_func = function(self, playedTime)
    return  { { text = "time limitation: 7 s", passed = playedTime >= 7 } }
  end,
  -- get_adjusted = function (self, player)
  --   if player.role == "lord" then
  --     return {hp = 10, maxHp = 10}
  --   end
  --   return {}
  -- end
}

Fk:loadTranslationTable{
  ["hx__simulator_mode"] = "忆者",
  [":hx__simulator_mode"] = desc_hx__simulator,
  ["#hx__simulator_rule&"] = "忆者规则",

  ["hx__simulator-intro"] = "忆者",
  [":hx__simulator-intro"] = [[
  <br/>忆者模式，每次开局，你将有不同的身份，在历险的过程中你将遇到各自各样的事件，多多探索，在忆境中大胜吧！
  <br/>每一次<b>抉择</b>都有可能导致「绝境」，请谨慎选择！
  <br/>]],
  ["@&hx__simulator_mode_lordgeneral"] = "真实",
  ["#hx__simulator_choose1"] = "这次，你是否要继续成为忆者呢？",
  ["#hx__simulator_choose1-1"] = "我非忆者，这是何意？",
  ["#hx__simulator_choose1-2"] = "熟悉的“抉择”吗……",
}

return hx__simulator_mode
